Document retrieval from wikipedia data

Fire up GraphLab Create


In [1]:
import graphlab

Load some text data - from wikipedia, pages on people


In [2]:
people = graphlab.SFrame('people_wiki.gl/')


[INFO] This non-commercial license of GraphLab Create is assigned to tuancrazy216@gmail.comand will expire on September 21, 2016. For commercial licensing options, visit https://dato.com/buy/.

[INFO] Start server at: ipc:///tmp/graphlab_server-6864 - Server binary: C:\Anaconda\envs\dato-env\lib\site-packages\graphlab\unity_server.exe - Server log: C:\Users\tvu\AppData\Local\Temp\graphlab_server_1444111262.log.0
[INFO] GraphLab Server Version: 1.6.1

Data contains: link to wikipedia article, name of person, text of article.


In [3]:
people.head()


Out[3]:
URI name text
<http://dbpedia.org/resou
rce/Digby_Morrell> ...
Digby Morrell digby morrell born 10
october 1979 is a former ...
<http://dbpedia.org/resou
rce/Alfred_J._Lewy> ...
Alfred J. Lewy alfred j lewy aka sandy
lewy graduated from ...
<http://dbpedia.org/resou
rce/Harpdog_Brown> ...
Harpdog Brown harpdog brown is a singer
and harmonica player who ...
<http://dbpedia.org/resou
rce/Franz_Rottensteiner> ...
Franz Rottensteiner franz rottensteiner born
in waidmannsfeld lower ...
<http://dbpedia.org/resou
rce/G-Enka> ...
G-Enka henry krvits born 30
december 1974 in tallinn ...
<http://dbpedia.org/resou
rce/Sam_Henderson> ...
Sam Henderson sam henderson born
october 18 1969 is an ...
<http://dbpedia.org/resou
rce/Aaron_LaCrate> ...
Aaron LaCrate aaron lacrate is an
american music producer ...
<http://dbpedia.org/resou
rce/Trevor_Ferguson> ...
Trevor Ferguson trevor ferguson aka john
farrow born 11 november ...
<http://dbpedia.org/resou
rce/Grant_Nelson> ...
Grant Nelson grant nelson born 27
april 1971 in london ...
<http://dbpedia.org/resou
rce/Cathy_Caruth> ...
Cathy Caruth cathy caruth born 1955 is
frank h t rhodes ...
[10 rows x 3 columns]


In [4]:
len(people)


Out[4]:
59071

Explore the dataset and checkout the text it contains

Exploring the entry for president Obama


In [5]:
obama = people[people['name'] == 'Barack Obama']

In [6]:
obama


Out[6]:
URI name text
<http://dbpedia.org/resou
rce/Barack_Obama> ...
Barack Obama barack hussein obama ii
brk husen bm born august ...
[? rows x 3 columns]
Note: Only the head of the SFrame is printed. This SFrame is lazily evaluated.
You can use len(sf) to force materialization.


In [7]:
obama['text']


Out[7]:
dtype: str
Rows: ?
['barack hussein obama ii brk husen bm born august 4 1961 is the 44th and current president of the united states and the first african american to hold the office born in honolulu hawaii obama is a graduate of columbia university and harvard law school where he served as president of the harvard law review he was a community organizer in chicago before earning his law degree he worked as a civil rights attorney and taught constitutional law at the university of chicago law school from 1992 to 2004 he served three terms representing the 13th district in the illinois senate from 1997 to 2004 running unsuccessfully for the united states house of representatives in 2000in 2004 obama received national attention during his campaign to represent illinois in the united states senate with his victory in the march democratic party primary his keynote address at the democratic national convention in july and his election to the senate in november he began his presidential campaign in 2007 and after a close primary campaign against hillary rodham clinton in 2008 he won sufficient delegates in the democratic party primaries to receive the presidential nomination he then defeated republican nominee john mccain in the general election and was inaugurated as president on january 20 2009 nine months after his election obama was named the 2009 nobel peace prize laureateduring his first two years in office obama signed into law economic stimulus legislation in response to the great recession in the form of the american recovery and reinvestment act of 2009 and the tax relief unemployment insurance reauthorization and job creation act of 2010 other major domestic initiatives in his first term included the patient protection and affordable care act often referred to as obamacare the doddfrank wall street reform and consumer protection act and the dont ask dont tell repeal act of 2010 in foreign policy obama ended us military involvement in the iraq war increased us troop levels in afghanistan signed the new start arms control treaty with russia ordered us military involvement in libya and ordered the military operation that resulted in the death of osama bin laden in january 2011 the republicans regained control of the house of representatives as the democratic party lost a total of 63 seats and after a lengthy debate over federal spending and whether or not to raise the nations debt limit obama signed the budget control act of 2011 and the american taxpayer relief act of 2012obama was reelected president in november 2012 defeating republican nominee mitt romney and was sworn in for a second term on january 20 2013 during his second term obama has promoted domestic policies related to gun control in response to the sandy hook elementary school shooting and has called for full equality for lgbt americans while his administration has filed briefs which urged the supreme court to strike down the defense of marriage act of 1996 and californias proposition 8 as unconstitutional in foreign policy obama ordered us military involvement in iraq in response to gains made by the islamic state in iraq after the 2011 withdrawal from iraq continued the process of ending us combat operations in afghanistan and has sought to normalize us relations with cuba', ... ]

Exploring the entry for actor George Clooney


In [8]:
clooney = people[people['name'] == 'George Clooney']
clooney['text']


Out[8]:
dtype: str
Rows: ?
['george timothy clooney born may 6 1961 is an american actor writer producer director and activist he has received three golden globe awards for his work as an actor and two academy awards one for acting and the other for producingclooney made his acting debut on television in 1978 and later gained wide recognition in his role as dr doug ross on the longrunning medical drama er from 1994 to 1999 for which he received two emmy award nominations while working on er he began attracting a variety of leading roles in films including the superhero film batman robin 1997 and the crime comedy out of sight 1998 in which he first worked with a director who would become a longtime collaborator steven soderbergh in 1999 clooney took the lead role in three kings a wellreceived war satire set during the gulf warin 2001 clooneys fame widened with the release of his biggest commercial success the heist comedy oceans eleven the first of the film trilogy a remake of the 1960 film with frank sinatra as danny ocean he made his directorial debut a year later with the biographical thriller confessions of a dangerous mind and has since directed the drama good night and good luck 2005 the sports comedy leatherheads 2008 the political drama the ides of march 2011 and the comedydrama war film the monuments men 2014he won an academy award for best supporting actor for the middle east thriller syriana 2005 and subsequently earned best actor nominations for the legal thriller michael clayton 2007 the comedydrama up in the air 2009 and the drama the descendants 2011 in 2013 he received the academy award for best picture for producing the political thriller argo alongside ben affleck and grant heslov he is the only person ever to be nominated for academy awards in six categoriesclooney is sometimes described as one of the most handsome men in the world in 2005 tv guide ranked clooney no 1 on its 50 sexiest stars of all time list in 2009 he was included in times annual time 100 as one of the most influential people in the world clooney is also noted for his political activism and has served as one of the united nations messengers of peace since january 31 2008 his humanitarian work includes his advocacy of finding a resolution for the darfur conflict raising funds for the 2010 haiti earthquake 2004 tsunami and 911 victims and creating documentaries such as sand and sorrow to raise awareness about international crises he is also a member of the council on foreign relations', ... ]

Get the word counts for Obama article


In [9]:
obama['word_count'] = graphlab.text_analytics.count_words(obama['text'])

In [10]:
print obama['word_count']


[{'operations': 1L, 'represent': 1L, 'office': 2L, 'unemployment': 1L, 'doddfrank': 1L, 'over': 1L, 'unconstitutional': 1L, 'domestic': 2L, 'major': 1L, 'years': 1L, 'against': 1L, 'proposition': 1L, 'seats': 1L, 'graduate': 1L, 'debate': 1L, 'before': 1L, 'death': 1L, '20': 2L, 'taxpayer': 1L, 'representing': 1L, 'obamacare': 1L, 'barack': 1L, 'to': 14L, '4': 1L, 'policy': 2L, '8': 1L, 'he': 7L, '2011': 3L, '2010': 2L, '2013': 1L, '2012': 1L, 'bin': 1L, 'then': 1L, 'his': 11L, 'march': 1L, 'gains': 1L, 'cuba': 1L, 'school': 3L, '1992': 1L, 'new': 1L, 'not': 1L, 'during': 2L, 'ending': 1L, 'continued': 1L, 'presidential': 2L, 'states': 3L, 'husen': 1L, 'osama': 1L, 'californias': 1L, 'equality': 1L, 'prize': 1L, 'lost': 1L, 'made': 1L, 'inaugurated': 1L, 'january': 3L, 'university': 2L, 'rights': 1L, 'july': 1L, 'gun': 1L, 'stimulus': 1L, 'rodham': 1L, 'troop': 1L, 'withdrawal': 1L, 'brk': 1L, 'nine': 1L, 'where': 1L, 'referred': 1L, 'affordable': 1L, 'attorney': 1L, 'on': 2L, 'often': 1L, 'senate': 3L, 'regained': 1L, 'national': 2L, 'creation': 1L, 'related': 1L, 'hawaii': 1L, 'born': 2L, 'second': 2L, 'defense': 1L, 'election': 3L, 'close': 1L, 'operation': 1L, 'insurance': 1L, 'sandy': 1L, 'afghanistan': 2L, 'initiatives': 1L, 'for': 4L, 'reform': 1L, 'house': 2L, 'review': 1L, 'representatives': 2L, 'current': 1L, 'state': 1L, 'won': 1L, 'limit': 1L, 'victory': 1L, 'unsuccessfully': 1L, 'reauthorization': 1L, 'keynote': 1L, 'full': 1L, 'patient': 1L, 'august': 1L, 'degree': 1L, '44th': 1L, 'bm': 1L, 'mitt': 1L, 'attention': 1L, 'delegates': 1L, 'lgbt': 1L, 'job': 1L, 'harvard': 2L, 'term': 3L, 'served': 2L, 'ask': 1L, 'november': 2L, 'debt': 1L, 'by': 1L, 'wall': 1L, 'care': 1L, 'received': 1L, 'great': 1L, 'signed': 3L, 'libya': 1L, 'receive': 1L, 'of': 18L, 'months': 1L, 'urged': 1L, 'foreign': 2L, 'american': 3L, 'protection': 2L, 'economic': 1L, 'act': 8L, 'military': 4L, 'hussein': 1L, 'or': 1L, 'first': 3L, 'control': 4L, 'named': 1L, 'clinton': 1L, 'dont': 2L, 'campaign': 3L, 'russia': 1L, 'civil': 1L, 'reinvestment': 1L, 'into': 1L, 'address': 1L, 'primary': 2L, 'community': 1L, 'mccain': 1L, 'down': 1L, 'hook': 1L, '63': 1L, 'americans': 1L, 'elementary': 1L, 'total': 1L, 'earning': 1L, 'repeal': 1L, 'from': 3L, 'raise': 1L, 'district': 1L, 'spending': 1L, 'republican': 2L, 'legislation': 1L, 'three': 1L, 'relations': 1L, 'nobel': 1L, 'start': 1L, 'tell': 1L, 'iraq': 4L, 'convention': 1L, 'resulted': 1L, 'john': 1L, 'was': 5L, '2012obama': 1L, 'form': 1L, 'that': 1L, 'tax': 1L, 'sufficient': 1L, 'republicans': 1L, 'strike': 1L, 'hillary': 1L, 'ended': 1L, 'arms': 1L, 'honolulu': 1L, 'filed': 1L, 'worked': 1L, 'hold': 1L, 'with': 3L, 'obama': 9L, 'street': 1L, 'ii': 1L, 'has': 4L, '1997': 1L, '1996': 1L, 'whether': 1L, 'reelected': 1L, 'budget': 1L, 'us': 6L, 'nations': 1L, 'recession': 1L, 'while': 1L, 'taught': 1L, 'marriage': 1L, 'policies': 1L, 'promoted': 1L, 'called': 1L, 'and': 21L, 'supreme': 1L, 'ordered': 3L, 'nominee': 2L, 'process': 1L, '2000in': 1L, 'is': 2L, 'romney': 1L, 'briefs': 1L, 'defeated': 1L, 'general': 1L, '13th': 1L, 'as': 6L, 'at': 2L, 'in': 30L, 'sought': 1L, 'organizer': 1L, 'shooting': 1L, 'increased': 1L, 'normalize': 1L, 'lengthy': 1L, 'united': 3L, 'court': 1L, 'recovery': 1L, 'laden': 1L, 'laureateduring': 1L, 'peace': 1L, 'administration': 1L, '1961': 1L, 'illinois': 2L, 'other': 1L, 'which': 1L, 'party': 3L, 'primaries': 1L, 'sworn': 1L, 'relief': 2L, 'war': 1L, 'columbia': 1L, 'combat': 1L, 'after': 4L, 'islamic': 1L, 'running': 1L, 'levels': 1L, 'two': 1L, 'involvement': 3L, 'response': 3L, 'included': 1L, 'president': 4L, 'law': 6L, 'nomination': 1L, '2008': 1L, 'a': 7L, '2009': 3L, 'chicago': 2L, 'constitutional': 1L, 'defeating': 1L, 'treaty': 1L, 'federal': 1L, '2007': 1L, '2004': 3L, 'african': 1L, 'the': 40L, 'democratic': 4L, 'consumer': 1L, 'began': 1L, 'terms': 1L}]

Sort the word counts for the Obama article

Turning dictonary of word counts into a table


In [11]:
obama_word_count_table = obama[['word_count']].stack('word_count', new_column_name = ['word','count'])

Sorting the word counts to show most common words at the top


In [12]:
obama_word_count_table.head()


Out[12]:
word count
normalize 1
sought 1
combat 1
continued 1
unconstitutional 1
8 1
californias 1
1996 1
marriage 1
defense 1
[10 rows x 2 columns]


In [13]:
obama_word_count_table.sort('count',ascending=False)


Out[13]:
word count
the 40
in 30
and 21
of 18
to 14
his 11
obama 9
act 8
a 7
he 7
[273 rows x 2 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.

Most common words include uninformative words like "the", "in", "and",...

Compute TF-IDF for the corpus

To give more weight to informative words, we weigh them by their TF-IDF scores.


In [14]:
people['word_count'] = graphlab.text_analytics.count_words(people['text'])
people.head()


Out[14]:
URI name text word_count
<http://dbpedia.org/resou
rce/Digby_Morrell> ...
Digby Morrell digby morrell born 10
october 1979 is a former ...
{'since': 1L, 'carltons':
1L, 'being': 1L, '2005': ...
<http://dbpedia.org/resou
rce/Alfred_J._Lewy> ...
Alfred J. Lewy alfred j lewy aka sandy
lewy graduated from ...
{'precise': 1L, 'thomas':
1L, 'closely': 1L, ...
<http://dbpedia.org/resou
rce/Harpdog_Brown> ...
Harpdog Brown harpdog brown is a singer
and harmonica player who ...
{'just': 1L, 'issued':
1L, 'mainly': 1L, ...
<http://dbpedia.org/resou
rce/Franz_Rottensteiner> ...
Franz Rottensteiner franz rottensteiner born
in waidmannsfeld lower ...
{'all': 1L,
'bauforschung': 1L, ...
<http://dbpedia.org/resou
rce/G-Enka> ...
G-Enka henry krvits born 30
december 1974 in tallinn ...
{'legendary': 1L,
'gangstergenka': 1L, ...
<http://dbpedia.org/resou
rce/Sam_Henderson> ...
Sam Henderson sam henderson born
october 18 1969 is an ...
{'now': 1L, 'currently':
1L, 'less': 1L, 'being': ...
<http://dbpedia.org/resou
rce/Aaron_LaCrate> ...
Aaron LaCrate aaron lacrate is an
american music producer ...
{'exclusive': 2L,
'producer': 1L, 'tribe': ...
<http://dbpedia.org/resou
rce/Trevor_Ferguson> ...
Trevor Ferguson trevor ferguson aka john
farrow born 11 november ...
{'taxi': 1L, 'salon': 1L,
'gangs': 1L, 'being': ...
<http://dbpedia.org/resou
rce/Grant_Nelson> ...
Grant Nelson grant nelson born 27
april 1971 in london ...
{'houston': 1L,
'frankie': 1L, 'labels': ...
<http://dbpedia.org/resou
rce/Cathy_Caruth> ...
Cathy Caruth cathy caruth born 1955 is
frank h t rhodes ...
{'phenomenon': 1L,
'deborash': 1L, ...
[10 rows x 4 columns]


In [15]:
tfidf = graphlab.text_analytics.tf_idf(people['word_count'])
tfidf


Out[15]:
docs
{'since':
1.455376717308041, ...
{'precise':
6.44320060695519, ...
{'just':
2.7007299687108643, ...
{'all':
1.6431112434912472, ...
{'legendary':
4.280856294365192, ...
{'now': 1.96695239252401,
'currently': ...
{'exclusive':
10.455187230695827, ...
{'taxi':
6.0520214560945025, ...
{'houston':
3.935505942157149, ...
{'phenomenon':
5.750053426395245, ...
[59071 rows x 1 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.


In [16]:
people['tfidf'] = tfidf['docs']

Examine the TF-IDF for the Obama article


In [17]:
obama = people[people['name'] == 'Barack Obama']

In [18]:
obama[['tfidf']].stack('tfidf',new_column_name=['word','tfidf']).sort('tfidf',ascending=False)


Out[18]:
word tfidf
obama 43.2956530721
act 27.678222623
iraq 17.747378588
control 14.8870608452
law 14.7229357618
ordered 14.5333739509
military 13.1159327785
involvement 12.7843852412
response 12.7843852412
democratic 12.4106886973
[273 rows x 2 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.

Words with highest TF-IDF are much more informative.

Manually compute distances between a few people

Let's manually compare the distances between the articles for a few famous people.


In [19]:
clinton = people[people['name'] == 'Bill Clinton']

In [20]:
beckham = people[people['name'] == 'David Beckham']

Is Obama closer to Clinton than to Beckham?

We will use cosine distance, which is given by

(1-cosine_similarity)

and find that the article about president Obama is closer to the one about former president Clinton than that of footballer David Beckham.


In [21]:
graphlab.distances.cosine(obama['tfidf'][0],clinton['tfidf'][0])


Out[21]:
0.8339854936884276

In [22]:
graphlab.distances.cosine(obama['tfidf'][0],beckham['tfidf'][0])


Out[22]:
0.9791305844747478

Build a nearest neighbor model for document retrieval

We now create a nearest-neighbors model and apply it to document retrieval.


In [23]:
knn_model = graphlab.nearest_neighbors.create(people,features=['tfidf'],label='name')


PROGRESS: Starting brute force nearest neighbors model training.

Applying the nearest-neighbors model for retrieval

Who is closest to Obama?


In [24]:
knn_model.query(obama)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 9ms          |
PROGRESS: | Done         |         | 100         | 451ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[24]:
query_label reference_label distance rank
0 Barack Obama 0.0 1
0 Joe Biden 0.794117647059 2
0 Joe Lieberman 0.794685990338 3
0 Kelly Ayotte 0.811989100817 4
0 Bill Clinton 0.813852813853 5
[5 rows x 4 columns]

As we can see, president Obama's article is closest to the one about his vice-president Biden, and those of other politicians.

Other examples of document retrieval


In [25]:
swift = people[people['name'] == 'Taylor Swift']

In [26]:
knn_model.query(swift)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 7ms          |
PROGRESS: | Done         |         | 100         | 467ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[26]:
query_label reference_label distance rank
0 Taylor Swift 0.0 1
0 Carrie Underwood 0.76231884058 2
0 Alicia Keys 0.764705882353 3
0 Jordin Sparks 0.769633507853 4
0 Leona Lewis 0.776119402985 5
[5 rows x 4 columns]


In [27]:
jolie = people[people['name'] == 'Angelina Jolie']

In [28]:
knn_model.query(jolie)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 5ms          |
PROGRESS: | Done         |         | 100         | 352ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[28]:
query_label reference_label distance rank
0 Angelina Jolie 0.0 1
0 Brad Pitt 0.784023668639 2
0 Julianne Moore 0.795857988166 3
0 Billy Bob Thornton 0.803069053708 4
0 George Clooney 0.8046875 5
[5 rows x 4 columns]


In [29]:
arnold = people[people['name'] == 'Arnold Schwarzenegger']

In [30]:
knn_model.query(arnold)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 6ms          |
PROGRESS: | Done         |         | 100         | 322ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[30]:
query_label reference_label distance rank
0 Arnold Schwarzenegger 0.0 1
0 Jesse Ventura 0.818918918919 2
0 John Kitzhaber 0.824615384615 3
0 Lincoln Chafee 0.833876221498 4
0 Anthony Foxx 0.833910034602 5
[5 rows x 4 columns]

Exercise

1) Compare top words according to word counts to TF-IDF

In the notebook we covered in the module, explored two document representations: word counts and TF-IDF. Now, take a particular famous person, 'Elton John'. What are the 3 words in his articles with highest word counts? What are the 3 words in his articles with highest TF-IDF? These results illustrate why TF-IDF is useful for finding important words. Save these results to answer the quiz at the end.


In [38]:
people.head(2)


Out[38]:
URI name text word_count
<http://dbpedia.org/resou
rce/Digby_Morrell> ...
Digby Morrell digby morrell born 10
october 1979 is a former ...
{'since': 1L, 'carltons':
1L, 'being': 1L, '2005': ...
<http://dbpedia.org/resou
rce/Alfred_J._Lewy> ...
Alfred J. Lewy alfred j lewy aka sandy
lewy graduated from ...
{'precise': 1L, 'thomas':
1L, 'closely': 1L, ...
tfidf
{'since':
1.455376717308041, ...
{'precise':
6.44320060695519, ...
[2 rows x 5 columns]


In [41]:
elton_john = people[people['name'] == 'Elton John']

In [42]:
elton_john.head()


Out[42]:
URI name text word_count
<http://dbpedia.org/resou
rce/Elton_John> ...
Elton John sir elton hercules john
cbe born reginald ken ...
{'all': 1L, 'six': 1L,
'producer': 1L, ...
tfidf
{'all':
1.6431112434912472, ...
[1 rows x 5 columns]


In [46]:
elton_john[['word_count']].stack('word_count', new_column_name = ['word','count']).sort('count',ascending=False)


Out[46]:
word count
the 27
in 18
and 15
of 13
a 10
has 9
he 7
john 7
on 6
since 5
[255 rows x 2 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.


In [48]:
elton_john[['tfidf']].stack('tfidf', new_column_name = ['word','tfidf']).sort('tfidf',ascending=False)


Out[48]:
word tfidf
furnish 18.38947184
elton 17.48232027
billboard 17.3036809575
john 13.9393127924
songwriters 11.250406447
overallelton 10.9864953892
tonightcandle 10.9864953892
19702000 10.2933482087
fivedecade 10.2933482087
aids 10.262846934
[255 rows x 2 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.

2) Measuring distance

Elton John is a famous singer; let’s compute the distance between his article and those of two other famous singers. In this assignment, you will use the cosine distance, which one measure of similarity between vectors, similar to the one discussed in the lectures. You can compute this distance using the graphlab.distances.cosine function. What’s the cosine distance between the articles on ‘Elton John’ and ‘Victoria Beckham’? What’s the cosine distance between the articles on ‘Elton John’ and Paul McCartney’? Which one of the two is closest to Elton John? Does this result make sense to you?


In [49]:
victoria_beckham = people[people['name'] == 'Victoria Beckham']

In [50]:
paul_mccartney = people[people['name'] == 'Paul McCartney']

In [51]:
graphlab.distances.cosine(elton_john['tfidf'][0],victoria_beckham['tfidf'][0])


Out[51]:
0.9567006376655429

In [52]:
graphlab.distances.cosine(elton_john['tfidf'][0], paul_mccartney['tfidf'][0])


Out[52]:
0.8250310029221779

3) Building nearest neighbors models with different input features and setting the distance metric

In the sample notebook, we built a nearest neighbors model for retrieving articles using TF-IDF as features and using the default setting in the construction of the nearest neighbors model. Now, you will build two nearest neighbors models:

  • Using word counts as features
  • Using TF-IDF as features

In both of these models, we are going to set the distance function to cosine similarity.

Here is how: when you call the function

graphlab.nearest_neighbors.create

add the parameter:

distance='cosine'

In [53]:
word_count_cosine_model = graphlab.nearest_neighbors.create(people,features=['word_count'],label='name',distance='cosine')


PROGRESS: Starting brute force nearest neighbors model training.

In [54]:
tfidf_cosine_model = graphlab.nearest_neighbors.create(people,features=['tfidf'],label='name',distance='cosine')


PROGRESS: Starting brute force nearest neighbors model training.

Now we are ready to use our model to retrieve documents. Use these two models to collect the following results:

What’s the most similar article, other than itself, to the one on ‘Elton John’ using word count features?


In [56]:
word_count_cosine_model.query(elton_john)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 7ms          |
PROGRESS: | Done         |         | 100         | 387ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[56]:
query_label reference_label distance rank
0 Elton John 2.22044604925e-16 1
0 Cliff Richard 0.16142415259 2
0 Sandro Petrone 0.16822542751 3
0 Rod Stewart 0.168327165587 4
0 Malachi O'Doherty 0.177315545979 5
[5 rows x 4 columns]

What’s the most similar article, other than itself, to the one on ‘Elton John’ using TF-IDF features?


In [57]:
tfidf_cosine_model.query(elton_john)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 7ms          |
PROGRESS: | Done         |         | 100         | 364ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[57]:
query_label reference_label distance rank
0 Elton John -2.22044604925e-16 1
0 Rod Stewart 0.717219667893 2
0 George Michael 0.747600998969 3
0 Sting (musician) 0.747671954431 4
0 Phil Collins 0.75119324879 5
[5 rows x 4 columns]

What’s the most similar article, other than itself, to the one on ‘Victoria Beckham’ using word count features?


In [59]:
word_count_cosine_model.query(victoria_beckham)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 10ms         |
PROGRESS: | Done         |         | 100         | 340ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[59]:
query_label reference_label distance rank
0 Victoria Beckham -2.22044604925e-16 1
0 Mary Fitzgerald (artist) 0.207307036115 2
0 Adrienne Corri 0.214509782788 3
0 Beverly Jane Fry 0.217466468741 4
0 Raman Mundair 0.217695474992 5
[5 rows x 4 columns]

What’s the most similar article, other than itself, to the one on ‘Victoria Beckham’ using TF-IDF features?


In [60]:
tfidf_cosine_model.query(victoria_beckham)


PROGRESS: Starting pairwise querying.
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time |
PROGRESS: +--------------+---------+-------------+--------------+
PROGRESS: | 0            | 1       | 0.00169288  | 8ms          |
PROGRESS: | Done         |         | 100         | 355ms        |
PROGRESS: +--------------+---------+-------------+--------------+
Out[60]:
query_label reference_label distance rank
0 Victoria Beckham 1.11022302463e-16 1
0 David Beckham 0.548169610263 2
0 Stephen Dow Beckham 0.784986706828 3
0 Mel B 0.809585523409 4
0 Caroline Rush 0.819826422919 5
[5 rows x 4 columns]